/*
 * Copyright 2021 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package internal

import (
	"bytes"
	"fmt"
	"net/http"

	log "github.com/sirupsen/logrus"
)

func SendData(url string, topic string) {

	err := getDataFromMqtt(url, topic)
	if err != nil {
		log.Error(err, "Send data failed")
	}
	return
}

func sendToHttp(url string, topic string, choke chan []byte) error {

	for true {
		readings := <-choke

		fmt.Printf("[sendToHttp]Input data:%v", string(readings))

		formatedData, err := formateData(readings, topic)
		if err != nil {
			log.Errorf("An Error Occured %v", err)
			return err
		}

		fmt.Printf("[sendToHttp]Formated data:%v", string(readings))

		responseBody := bytes.NewBuffer(formatedData)

		resp, err := http.Post(url, "application/json", responseBody)
		//Handle Error
		if err != nil {
			log.Errorf("An Error Occured %v", err)
			return err
		}
		defer resp.Body.Close()
	}

	return nil
}
